package com.cssl.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cssl.domain.DtsCategory;
import com.cssl.domain.DtsGoods;
import com.cssl.domain.dto.DtsCategoryDto;
import com.cssl.mapper.DtsCategoryMapper;
import com.cssl.service.DtsCategoryService;
import com.cssl.util.InfoCode;
import com.cssl.util.ObjectMapperUtil;
import com.cssl.util.Result;
import com.cssl.util.StorageVariable;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;


@Service
public class DtsCategoryServiceImpl implements DtsCategoryService {
    @Autowired
    private DtsCategoryMapper mapper;
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private ObjectMapperUtil objectMapperUtil;

    @Override
    public List<DtsCategory> getCategory(String levels, Integer id) {
        //存储redis类型为String

        //判断获取一级分类还是二及分类
        boolean flag = false;
        if ("L1".equals(levels)) {
            flag = true;
        }
        //判断redis是否存在数据
        Object o = null;
        if (flag) {
            //一级分类
            o = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + "L1");
        } else {
            o = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + id);
        }
        //不存在
        ObjectMapper objectMapper = new ObjectMapper();
        if (ObjectUtil.isEmpty(o)) {
            //从数据库查询
            List<DtsCategory> categoryList = flag
                    ? mapper.getCategory("L1", 0)
                    : mapper.getCategory("L2", id);
            //添加
            if (flag) {
                template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + "L1", objectMapperUtil.toJsonString(categoryList), 7, TimeUnit.DAYS);
            } else {
                template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + id, objectMapperUtil.toJsonString(categoryList), 7, TimeUnit.DAYS);
            }
            return categoryList;
        }

        //存在
        List<DtsCategory> category;
        category = objectMapperUtil.fromJsonString(o.toString(), new TypeReference<List<DtsCategory>>() {
        });
        return category;
    }

    @Override
    public Page getLevel3(Integer pages, Integer size, Integer categoryId) {
        //先从redis(String类型)查询(key:"category:goods"+":"+二级id+":"+页数)
        String s = template.opsForValue().get(StorageVariable.LEVELTHREE_GOODS + ":" + categoryId + ":" + pages);
        if (StrUtil.isEmpty(s)) {
            Page page = PageHelper.startPage(pages, 10);
            //为空(查询数据库)
            List<DtsGoods> level3 = mapper.getLevel3(categoryId);
            template.opsForValue().set(StorageVariable.LEVELTHREE_GOODS + ":" + categoryId + ":" + pages, objectMapperUtil.toJsonString(level3), 7, TimeUnit.DAYS);
            return page;
        }
        //不为空
        List<DtsGoods> goods = objectMapperUtil.fromJsonString(s, new TypeReference<List<DtsGoods>>() {
        });
        Page page = new Page();
        page.addAll(goods);
        page.setPageNum(pages);
        page.setPageSize(size);
        page.setTotal(goods.size());
        return page;
    }

    @Override
    public Result getL1AndL2() {
        //从redis中获取所有的一级分类,及对应的二级分类
        String redis = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + "L1");
        List<DtsCategory> s1 = null;
        List<DtsCategory> s2 = null;
        Map map = new HashMap();
        if (StrUtil.isEmpty(redis)) {
            //一级分类为空
            s1 = mapper.getCategory("L1", 0);
            map.put("L1List", s1);
            map.put("checkedL1", s1.get(0));
            Integer checkedId = s1.get(0).getId();
            //从redis查询二级分类
            String redis2 = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + checkedId);
            if (StrUtil.isEmpty(redis2)) {
                //二级分类为空
                s2 = mapper.getCategory("L2", checkedId);
                //存储二级分类进入redis
                template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + s1.get(0).getId(), objectMapperUtil.toJsonString(s2));
                map.put("checkedL2", s2);
                return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
            }
            //二级分类不为空
            s2 = objectMapperUtil.fromJsonString(redis2, new TypeReference<List<DtsCategory>>() {
            });
            map.put("checkedL2", s2);
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
        }
        //一级分类不为空
        s1 = objectMapperUtil.fromJsonString(redis, new TypeReference<List<DtsCategory>>() {
        });
        map.put("L1List", s1);
        map.put("checkedL1", s1.get(0));
        //查询二及分类
        //从redis查询二级分类
        String redis2 = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + s1.get(0).getId());
        if (StrUtil.isEmpty(redis2)) {
            //二级分类为空
            s2 = mapper.getCategory("L2", s1.get(0).getId());
            //存储二级分类进入redis
            template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + s1.get(0).getId(), objectMapperUtil.toJsonString(s2));
            map.put("checkedL2", s2);
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
        }
        //二级分类不为空
        s2 = objectMapperUtil.fromJsonString(redis2, new TypeReference<List<DtsCategory>>() {
        });
        map.put("checkedL2", s2);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
    }


    @Override
    public Result clickL1GetL2(Integer id) {
        //先从redis中获取一级id对应的分类
        String redis = template.opsForValue().get(StorageVariable.CATEGORY_KEY_L1 + id);
        DtsCategory checkedList = null;
        List<DtsCategory> checkedListL2 = null;
        Map map = new HashMap();
        if (StrUtil.isEmpty(redis)) {
            //为空
            checkedList = mapper.getLevel1(id);
            template.opsForValue().set(StorageVariable.CATEGORY_KEY_L1 + id, objectMapperUtil.toJsonString(checkedList));
            map.put("L1List", checkedList);
            //redis获得二级分类
            String redis2 = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + id);
            if (StrUtil.isEmpty(redis2)) {
                //二级分类为空
                checkedListL2 = mapper.getCategory("L2", id);
                //存储二级分类进入redis
                template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + id, objectMapperUtil.toJsonString(checkedListL2));
                map.put("checkedL2", checkedListL2);
                return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
            }
            checkedListL2 = objectMapperUtil.fromJsonString(redis2, new TypeReference<List<DtsCategory>>() {
            });
            map.put("checkedL2", checkedListL2);
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
        }
        //一级分类不为空
        checkedList = objectMapperUtil.fromJsonString(redis, new TypeReference<DtsCategory>() {
        });
        map.put("L1List", checkedList);
        //查询二及分类
        //从redis查询二级分类
        String redis2 = template.opsForValue().get(StorageVariable.CATEGORY_KEY + ":" + id);
        if (StrUtil.isEmpty(redis2)) {
            //二级分类为空
            checkedListL2 = mapper.getCategory("L2", id);
            //存储二级分类进入redis
            template.opsForValue().set(StorageVariable.CATEGORY_KEY + ":" + id, objectMapperUtil.toJsonString(checkedListL2));
            map.put("checkedL2", checkedListL2);
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
        }
        //二级分类不为空
        checkedListL2= objectMapperUtil.fromJsonString(redis2, new TypeReference<List<DtsCategory>>() {
        });
        map.put("checkedL2", checkedListL2);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
    }

    @Override
    public Result getLevel2AndCheckedL2(DtsCategory category) {
        Integer id = category.getId();
        Integer pId = category.getpId();
        //先从redis获得pid为二级分类
        String s = template.opsForValue().get(StorageVariable.CATEGORY_KEY_L2 + ":" + pId);
        Map map = new HashMap();
        if (StrUtil.isEmpty(s)) {
            //为空
            List<DtsCategory> l2 = mapper.getCategory("L2", pId);
            template.opsForValue().set(StorageVariable.CATEGORY_KEY_L2 + ":" + pId, objectMapperUtil.toJsonString(l2));
            Optional<DtsCategory> first = l2.stream()
                    .filter(c -> c.getId().equals(id))
                    .findFirst();
            map.put("L2List", l2);
            map.put("checkedL2", first);
            return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
        }
        //不为空
        List<DtsCategory> categoryList = objectMapperUtil.fromJsonString(s, new TypeReference<List<DtsCategory>>() {
        });
        Optional<DtsCategory> first = categoryList.stream()
                .filter(c -> c.getId().equals(id))
                .findFirst();
        map.put("L2List", categoryList);
        map.put("checkedL2", first);
        return Result.result(InfoCode.OK, InfoCode.MESSAGE_OK, map, System.currentTimeMillis());
    }

    @Override
    public Map findPagecategory(DtsCategoryDto dtsCategoryDto) {
        System.out.println("传入" +dtsCategoryDto);
        Page page = PageHelper.startPage(dtsCategoryDto.getPage(),dtsCategoryDto.getLimit());

        List<DtsCategory> categroys=mapper.findPagecategory(dtsCategoryDto);
        System.out.println("查询结果: " + categroys); // 打印查询结果
        System.out.println("分页结果: " + page.getResult()); // 打印分页结果
        Map map = new HashMap();
        map.put("list", page.getResult());
        map.put("total", page.getTotal());
        map.put("totalPage", page.getPages());
        map.put("pageNum", page.getPageNum());
        map.put("pageSize", page.getPageSize());
        return map;
    }

    @Override
    public boolean categorydelete(String ids) {
        return mapper.categorydelete(ids);
    }

    @Override
    public Integer updatecategory(Map map) {
        return mapper.updatecategory(map);
    }

    @Override
    public Integer addcategory(Map map) {
        return mapper.addcategory(map);
    }
}
